package com.xinxing.city.recoverycheck;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.INT_PTR;
import com.hikvision.netsdk.NET_DVR_JPEGPARA;
import com.hikvision.netsdk.NET_DVR_PREVIEWINFO;
import com.xinxing.city.recoverycheck.Control.SDKGuider;
import com.xinxing.city.recoverycheck.jna.HCNetSDKByJNA;
import com.xinxing.city.recoverycheck.jna.HCNetSDKJNAInstance;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class HKActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    private SurfaceView m_surfaceView = null;
    private int m_iPreviewHandle = -1;
    private SurfaceHolder holder;
    private String userip = "192.168.1.64";
    private String username = "admin";
    private String userpassward = "Xx135246";
    private int port = 8000;
    private ImageView imageview;
    private Button start, refresh, stop;
    private int lUserID;
    private boolean play = false;
    private int k = 0;
    String ALBUM_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+"/hk/";
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hk);
        start = findViewById(R.id.button_preview_start);
        m_surfaceView = findViewById(R.id.Surface_Preview_Play);
        holder = m_surfaceView.getHolder();
        imageview = findViewById(R.id.image);
        refresh = findViewById(R.id.button_refresh);
        m_surfaceView.getHolder().addCallback(this);
        m_surfaceView.setZOrderOnTop(true);
        stop = findViewById(R.id.button_stop);
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Stop_jni(m_iPreviewHandle);
                play = false;
//                Canvas canvas = null;
//                canvas=holder.lockCanvas();
//                Paint p = new Paint();
//                Rect r = new Rect(10, 5, 30, 25);
//                canvas.drawRect(r, p);
//                holder.unlockCanvasAndPost(canvas);
            }
        });
        HCNetSDK.getInstance().NET_DVR_Init();
        if (m_iPreviewHandle != -1) {
            SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Stop_jni(m_iPreviewHandle);
        }
        HCNetSDKByJNA.NET_DVR_USER_LOGIN_INFO loginInfo = new HCNetSDKByJNA.NET_DVR_USER_LOGIN_INFO();
        System.arraycopy(userip.getBytes(), 0, loginInfo.sDeviceAddress, 0, userip.length());
        System.arraycopy(username.getBytes(), 0, loginInfo.sUserName, 0, username.length());
        System.arraycopy(userpassward.getBytes(), 0, loginInfo.sPassword, 0, userpassward.length());
        loginInfo.wPort = (short) port;
        HCNetSDKByJNA.NET_DVR_DEVICEINFO_V40 deviceInfo = new HCNetSDKByJNA.NET_DVR_DEVICEINFO_V40();
        loginInfo.write();
        lUserID = HCNetSDKJNAInstance.getInstance().NET_DVR_Login_V40(loginInfo.getPointer(), deviceInfo.getPointer());
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                m_surfaceView.getHolder().addCallback(HKActivity.this);
                m_surfaceView.setZOrderOnTop(true);
                m_surfaceView.setVisibility(View.VISIBLE);
                SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlaySurfaceChanged_jni(m_iPreviewHandle, 0, holder);
                NET_DVR_PREVIEWINFO struPlayInfo = new NET_DVR_PREVIEWINFO();
                struPlayInfo.lChannel = 1;
                struPlayInfo.dwStreamType = 0;
                struPlayInfo.bBlocked = 1;
                struPlayInfo.hHwnd = m_surfaceView.getHolder();
                m_iPreviewHandle = SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_V40_jni(0, struPlayInfo, null);
                if (m_iPreviewHandle < 0) {
                    Toast.makeText(HKActivity.this, "NET_DVR_RealPlay_V40 fail, Err:" + SDKGuider.g_sdkGuider.GetLastError_jni(), Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(HKActivity.this, "NET_DVR_RealPlay_V40 Succ ", Toast.LENGTH_SHORT).show();
            }
        });
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Stop_jni(m_iPreviewHandle);
                m_surfaceView.setVisibility(View.INVISIBLE);
                play = true;
                refreshThread(k);
                k++;
            }
        });
        findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SDKGuider.g_sdkGuider.m_comConfGuider.Test_PTZControl(m_iPreviewHandle);
            }
        });
        findViewById(R.id.right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SDKGuider.g_sdkGuider.m_comConfGuider.Test_PTZControlWithSpeed(m_iPreviewHandle);
            }
        });
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        m_surfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        if (-1 == m_iPreviewHandle) {
            return;
        }
        Surface surface = holder.getSurface();
        if (surface.isValid()) {
            if (-1 == SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlaySurfaceChanged_jni(m_iPreviewHandle, 0, holder))
                Toast.makeText(HKActivity.this, "NET_DVR_PlayBackSurfaceChanged" + SDKGuider.g_sdkGuider.GetLastError_jni(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        if (-1 == m_iPreviewHandle) {
            return;
        }
        if (holder.getSurface().isValid()) {
            if (-1 == SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlaySurfaceChanged_jni(m_iPreviewHandle, 0, null)) {
                Toast.makeText(HKActivity.this, "NET_DVR_RealPlaySurfaceChanged" + SDKGuider.g_sdkGuider.GetLastError_jni(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void refreshThread(int l) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                NET_DVR_JPEGPARA PARA = new NET_DVR_JPEGPARA();
                PARA.wPicQuality = 0;
                PARA.wPicSize = 13;
                int iBufferSize = 2448 * 2048;

                byte[] sbuffer = new byte[iBufferSize];
                INT_PTR bytesRerned = new INT_PTR();
                boolean flag = HCNetSDK.getInstance().NET_DVR_CaptureJPEGPicture_NEW(lUserID, 1, PARA, sbuffer, iBufferSize, bytesRerned);
                if (flag) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(sbuffer, 0, sbuffer.length);
//                    bytesToImageFile(sbuffer, "picImage" + l);
                    byteArrayToFile(sbuffer,ALBUM_PATH+"imagePic"+l+".jpg");
//                    try {
////                        saveFile(bitmap,"imagePic"+l+".jpg");
//
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageview.setImageBitmap(bitmap);


                        }
                    });
                } else {
                    Log.e("frame", "NET_DVR_ERROR:" + HCNetSDK.getInstance().NET_DVR_GetLastError());
                }
            }
        }).start();
    }
    public static void  byteArrayToFile(byte[] src,String filePath) {
        //1.创建源
        File file = new File(filePath);
        //选择流
        InputStream writing = null;
        OutputStream os = null;
        try {
            writing = new ByteArrayInputStream(src);
            os = new FileOutputStream(file);
            byte[]  frush = new byte[5];//3表示0个字节为一段
            int len = -1;
            while((len=writing.read(frush))!=-1) {
                os.write(frush,0,len);
            }
            os.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 保存文件
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(ALBUM_PATH);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

}
